﻿using eDataBoard.basePage;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System;
using OpcSelfHost.WebApi.model;
using Newtonsoft.Json;
using OpcSelfHost.basePage;
using S7PlcHelper;
using S7.Net;
using System.Data;

namespace OpcSelfHost.WebApi.controllers
{
    [RoutePrefix("api")]
    public class PlcController : ApiController
    {
        /// <summary>
        /// 接口检查
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public bool start(JObject jsonObj)
        {
            try
            {
                string plcip = (string)jsonObj.GetValue("plcip"); 

                PlcConfig mPlcConfig = CommonBase.mPlcConfigs.FirstOrDefault(t => t.ip == plcip);
                if (mPlcConfig == null)
                {
                    return false; 
                }
                PlcHelper plc = new PlcHelper(mPlcConfig);
                plc.Open();
                plc.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }

        public static readonly object lockobj = new Object();
        /// <summary>
        /// 读取plc db的值
        /// </summary>
        /// <param name="jsonObj">db：int(cpu序号),startadr：开始位置，count：读取多少位；struct:数据结构[{title:"neme",type:"BOOL"},{title:"neme2",type:"BOOL"}],按顺序排列</param>
        /// <returns></returns>
        [HttpPost]
        public ReturnMsg read(JObject jsonObj)
        {
            object return_data = null;
            string return_msg = null;
            try
            {
                lock (lockobj)
                {

                    string plcip = (string)jsonObj.GetValue("plcip");
                    int db = (int)jsonObj.GetValue("db");
                    int startadr = (int)jsonObj.GetValue("startadr"); 
                    int count = (int)jsonObj.GetValue("count");
                    JToken structs = jsonObj.GetValue("struct");

                    PlcConfig mPlcConfig =   CommonBase.mPlcConfigs.FirstOrDefault(t => t.ip == plcip);
                    if (mPlcConfig==null)
                    {
                       return ReturnMsg.setReturnMsg(1, "连接异常", return_data);

                    } 

                    PlcHelper plc = new PlcHelper(mPlcConfig); 
                    List<PlcTag> PlcTags = structs.Select(s => new PlcTag()
                    {
                        title = s.Value<string>("title"),
                        type = s.Value<string>("type")
                    }).ToList();

                    plc.Open();
                    if (plc.IsConnected)
                    {

                        // DataType: 数据类型，DB或Memory等
                        // DB : DataBlock=1，Memory=0
                        // count : 偏移量(offset)，设置多少就获取到具体位置的数据
                        // eg: 比如最后一个DBW是16，那么数据类型长度为2，count就需要传18才能获取到
                        byte[] bytes = plc.ReadBytes(DataType.DataBlock, db, startadr, count);

                        object return_obj = plc.bytes2obj(bytes, PlcTags);
                        plc.Close();
                        return ReturnMsg.setReturnMsg(0, return_msg, return_obj);
                    }
                    else
                    {
                        return ReturnMsg.setReturnMsg(1, "连接异常", return_data);
                    }


                }
            }
            catch (Exception ex)
            {
                return_msg = ex.Message;
                return ReturnMsg.setReturnMsg(1, return_msg, return_data);
            }

        }





    }
}
